<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | XFireSmsHelper.php v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018/11/28
// +-------------------------------------------------------------------------------

namespace app\extend\sms;


use common\Random;
use sms\SmsHelper;
use think\Cache;
use think\Log;

class XFireSmsHelperImpl implements SmsHelper {
    private $url;

    public function __construct($url) {
        $this->url = $url;
    }

    public function sendVerify($mobile,
                               $expired = 600,
                               $code = false,
                               $type = "",
                               $uid = -1,
                               $message = false) {
        if (!$code) {
            $code = Random::get(4, false, true, false, false);
        }
        $cacheKey = $this->_getCacheKey($mobile, $type, $uid);
        $msg = str_replace("[code]", $code, SmsHelper::DEFAULT_VERIFY_CODE_MESSAGE);
        $this->_doSend($mobile, $msg);
        Cache::set($cacheKey, $code, $expired);
        return [
            'status' => 1,
            'info' => '成功'
        ];
    }

    public function checkVerify($mobile, $code, $type = "", $uid = -1) {
        $cacheKey = $this->_getCacheKey($mobile, $type, $uid);
        $val = Cache::get($cacheKey);
        Cache::rm($cacheKey);
        if ($code == $val) {
            return [
                'status' => 1,
                'info' => '成功'
            ];
        }
        return [
            'status' => 0,
            'info' => '失败'
        ];
    }

    public function send($mobile, $msg) {
        $this->_doSend($mobile, $msg);
        return [
            'status' => 1,
            'info' => '成功'
        ];
    }

    private function _doSend($phone, $content) {
        $client = new \SoapClient($this->url);
        $response = $client->sendMessageNomal([
            'in0' => $content,
            'in1' => $phone
        ]);
        Log::record(json_encode($response), "SMS");
    }

    /**
     * @param $mobile
     * @param $type
     * @param $uid
     * @return string
     */
    private function _getCacheKey($mobile, $type, $uid) {
        $cacheKey = "__XFIRE_SMS_CACHE_PREFIX." . md5(json_encode([
                'mobile' => $mobile,
                'type' => $type,
                'uid' => $uid
            ]));
        return $cacheKey;
    }
}